from importlib import import_module

from django.apps import AppConfig
from django.conf import settings
from django.db import models


class CommentConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'comment'
    OBJECT_MODEL_CLASS = None

    def ready(self):
        self._add_fields()

    def _add_fields(self):
        """
        Reading settings and add article field to "Comment" model dynamically
        """
        # Load user defined settings or default
        from .models import Comment
        object_model_classes = getattr(settings, 'COMMENT_OBJECT_MODEL_CLASS', 'article.models.Article')
        class_splits = object_model_classes.split('.')
        module = '.'.join(class_splits[:-1])
        class_name = class_splits[-1]
        try:
            model_module = import_module(module)
        except ImportError:
            raise ImportError(
                f'The module "{module}" can not be found, '
                f'or you can override "COMMENT_OBJECT_MODEL_CLASSES" in settings.py.'
            )
        model_class = getattr(model_module, class_name)
        if not model_class:
            raise ImportError(f'Can not find class name "{class_name}" in module "{module}".')
        setattr(self, 'OBJECT_MODEL_CLASS', model_class)

        # Add field to comment
        foreignkey_field = models.ForeignKey(
            to=model_class, on_delete=models.DO_NOTHING, verbose_name='文章',
            related_name=f'{class_name.lower()}_comments'
        )
        Comment.add_to_class('article', foreignkey_field)
